<?php
namespace App\Forms;

use App\Exceptions\RequestException;
use App\Models\GoodsSkuAttribute;

/**
 * Created by lzl
 * Date: 2021 2021/10/15
 * Time: 17:16
 */

class StockForms extends BaseForm
{

    /**
     * 处理库存
     * @param $attribute_id
     * @param $stock | 加库存为正数 减库存为负数
     * @return int
     * @throws RequestException
     */
    public function editStock($attribute_id, $stock)
    {
        //TODO 加锁防止并发
        $attribute = GoodsSkuAttribute::find($attribute_id);

        if($stock < 0){
            $this->compareStock($attribute, -$stock);
        }


        return $attribute->increment('stock', $stock);


    }


    /**
     * 对比库存
     * @param GoodsSkuAttribute $attribute
     * @param $stock
     * @throws RequestException
     */
    public function compareStock(GoodsSkuAttribute $attribute, $stock)
    {
        if( $attribute->stock < $stock ){
            throw new RequestException('商品 '.$attribute->goods->goods_name.' 库存不足');
        }
    }


}